package com.upc.sealback.utils.DigitalCertificate;

import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfImageObject;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import com.upc.sealback.utils.ByteUtils;
import lombok.Data;
import lombok.SneakyThrows;


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.upc.sealback.utils.FontUtils.SEAL_SAVE_PATH;

/**
 * @description 数字签名信息实现类
 * @create zymac
 * @date 2022/5/31 20:25
 **/
@Data
public class ExtImageRenderListener implements RenderListener {
    private int i;
    private String basePath;
    @Override
    public void beginTextBlock() {

    }

    public void setBasePath(String basePath) {
        if (basePath.endsWith("/")) {
            this.basePath = basePath;
        } else {
            this.basePath = basePath + "/";
        }
    }

    public void setI(int i) {
        this.i = i;
    }


    @Override
    public void renderText(TextRenderInfo renderInfo) {

    }

    @Override
    public void endTextBlock() {

    }

    PdfDictionary resources;

    List<List<Integer>> numbers = new ArrayList<>();

    @SneakyThrows
    @Override
    public void renderImage(ImageRenderInfo renderInfo) {
        PdfImageObject image = renderInfo.getImage();
        if (image == null) {
            System.out.println("Image {} could not be read "+renderInfo.getRef().getNumber());
            return;
        }

        BufferedImage bufferedImage = image.getBufferedImage();
        if (bufferedImage != null) {
            System.out.println("bufferedImage: {} "+bufferedImage.getHeight());

            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            BufferedImage to = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = to.createGraphics();
            to = g2d.getDeviceConfiguration().createCompatibleImage(width,height, Transparency.TRANSLUCENT);
            g2d.dispose();
            g2d = to.createGraphics();
            Image from = bufferedImage.getScaledInstance(width, height, bufferedImage.SCALE_AREA_AVERAGING);
            g2d.drawImage(from, 0, 0, null);
            g2d.dispose();


            writeImage(bufferedImage);
        }

    }


    private void writeImage(BufferedImage bufferedImage) {
        try {
            File file = new File(basePath + i + ".png");
            if (file.exists()) {
                return;
            }
            System.out.println("generated image: {}"+file.getPath());

            ImageIO.write(bufferedImage, "png", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
